<template>
  <view class="login">
    <!-- <up-swiper :list="list1"
            circular
            ></up-swiper> -->
    <view class="upbutton">
      <up-button type="primary" @click="showPopup = true">账号登录</up-button>
    </view>
    
    <up-popup :show="showPopup" @close="close" @open="open">
      <view class="form">
        <view class="sign-up">
          <template v-if="!isAdministrator">
            <text :class="{ active: clickIndex == 1 }" @click="signUp(1)">登录</text>
            <text :class="{ active: clickIndex == 2 }" @click="signUp(2)">注册</text>
          </template>
          <text v-else :class="{ active: isAdministrator }">管理员登录</text>
        </view>
        <view class="upform">
          <up-form
            labelPosition="left"
            :model="modelForm"
            :rules="modelForm.rules"
            ref="formRef"
          >
            <up-form-item prop="userInfo.mobile">
              <up-input
                prefixIcon="phone"
                size="large"
                :customStyle="customStyle"
                placeholder="请输入手机号"
                v-model="modelForm.userInfo.mobile"
                @blur="validateMobile"
                @input="onMobileInput"
              ></up-input>
              <view v-if="mobileTouched && mobileError" class="error-tip">{{ mobileError }}</view>
            </up-form-item>
            <up-form-item prop="userInfo.password">
              <up-input
                prefixIcon="lock"
                size="large"
                :customStyle="customStyle"
                placeholder="请输入密码"
                :password="true"
                v-model="modelForm.userInfo.password"
                @blur="validatePassword"
                @input="onPasswordInput"
              ></up-input>
              <view v-if="passwordTouched && passwordError" class="error-tip">{{ passwordError }}</view>
            </up-form-item>

            <up-form-item prop="userInfo.code">

              <view style="width: 100%;margin: 0px;height: 30px;display: flex;flex-direction: row; align-items: center;">
   
                <up-input
                  prefixIcon="lock"
                  size="large"
                  maxlength="4"
                  :customStyle="{height: '30px', marginRight: '10px',width:'60%'}"
                  placeholder="请输入验证码"
                  v-model="modelForm.userInfo.code"
                ></up-input>


                <view class="login-code">
                  <image :src="codeUrl" @click="getCode" class="login-code-img"></image>
                </view>
            </view> 
            </up-form-item>
          </up-form>
        </view>

        <template v-if="!isAdministrator">
          <view class="logo-text terms">
            <up-checkbox
              :customStyle="{ fontSize: '14px' }"
              label="我已阅读并同意"
              name="agree"
              usedAlone
              v-model="checked"
            >
            </up-checkbox>
            <text>《服务条款》</text>
            <text>和</text>
            <text>《隐私政策》</text>
          </view>
        </template>
        <view class="logo-text terms">
          <up-button
            type="primary"
            :disabled="!checked"
            color="#0052d9"
            @click="submit"
            text="登录"
          ></up-button>
        </view>
        <view class="logo-text" :class="{ active: isAdministrator }" style="justify-content: flex-end;">
          <!-- <text @click="signUp(3)" v-if="!isAdministrator">管理员登录</text> -->
          <text @click="signUp(4)" v-if="!isAdministrator">忘记密码？</text>
          <!-- <text @click="signUp(5)" v-if="isAdministrator">返回用户登录</text> -->
        </view>
        <!-- <template v-if="!isAdministrator">
          <view class="logo-text terms other-logins">
            <text>其他登录方式</text>
          </view>
          <view class="logon-footer">
            <up-icon
              name="weixin-circle-fill"
              color="#07c160"
              size="40"
              @click="navigateTo(`/indexPages/index/index`)"
            ></up-icon>
            <text>微信一键登录</text>
          </view>
        </template> -->
        <view class="company">
          <text class="text" v-if="isAdministrator">
            登录即表示同意《服务条款》和《隐私政策》</text>
          <text>Copyright @ 2024版权所有</text>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { login, getCodeImg } from '@/api/login';
import { useUserStore } from '@/store/user';
import { useUserIdentity } from '@/composables/useUserIdentity';
import { ref } from 'vue';
const captchaEnabled = ref(true); // 是否开启验证码
const codeUrl = ref("");
const showPopup = ref<any>();
const checked = ref<any>(true); // 默认勾选，允许用户直接登录
const clickIndex = ref<Number>(1);
const mobileError = ref(""); // 手机号错误提示
const mobileTouched = ref(false); // 手机号是否已触碰
const passwordError = ref(""); // 密码错误提示
const passwordTouched = ref(false); // 密码是否已输入过

const modelForm = ref<any>({
  userInfo: {
    mobile: "",
    password: "",
    code:'',
    uuid:'',
  },
  rules: {
    "userInfo.mobile": {
      type: "string",
      required: false,
      trigger: ["blur", "change"],
    },
    "userInfo.password": {
      type: "string",
      required: false,
      trigger: ["blur", "change"],
    },
    "userInfo.code": {
      type: "string",
      required: true,
      message: "请输入验证码",
      trigger: ["blur", "change"],
    },
  },
});
const customStyle = ref<any>({
  height: "30px",
});
const isAdministrator = ref<any>(false);
const formRef = ref<any>(null);
const close = () => {};
const open = () => {};
const signUp = (index: Number) => {
  clickIndex.value = index;
  modelForm.value.userInfo = {};
  switch (index) {
    case 1:
      break;
    case 2:
      navigateTo(`/pages/logon/register`);
      break;
    case 3:
      isAdministrator.value = true;
      checked.value = true;
      uni.setNavigationBarTitle({
        title: "管理员登录",
      });
      break;
    case 4:
      navigateTo(`/pages/logon/forgotPassword`);
      break;
    case 5:
      clickIndex.value = 1;
      checked.value = true; // 保持勾选状态
      isAdministrator.value = false;
      uni.setNavigationBarTitle({
        title: "账号登录",
      });
      break;
    default:
  }
};

// 手机号输入时的实时验证（只在已触碰后才验证）
const onMobileInput = () => {
  if (mobileTouched.value) {
    validateMobile();
  }
};

// 手机号格式验证
const validateMobile = () => {
  mobileTouched.value = true;
  const mobile = modelForm.value.userInfo.mobile;
  
  if (!mobile) {
    mobileError.value = "请输入手机号";
    return;
  }
  
  if (!/^1[3-9]\d{9}$/.test(mobile)) {
    mobileError.value = "请输入正确的手机号码";
    return;
  }
  
  mobileError.value = "";
};

// 密码输入时的实时验证（只在已触碰后才验证）
const onPasswordInput = () => {
  if (passwordTouched.value) {
    validatePassword();
  }
};

// 密码格式验证
const validatePassword = () => {
  passwordTouched.value = true; // 标记为已触碰过
  const password = modelForm.value.userInfo.password;
  
  if (!password) {
    passwordError.value = "请输入密码";
    return;
  }
  
  if (password.length < 8 || password.length > 20) {
    passwordError.value = "密码长度必须为8-20位";
    return;
  }
  
  const hasUpperCase = /[A-Z]/.test(password);
  const hasLowerCase = /[a-z]/.test(password);
  const hasNumber = /[0-9]/.test(password);
  
  if (!hasUpperCase || !hasLowerCase || !hasNumber) {
    passwordError.value = "密码必须同时包含大写字母、小写字母和数字";
    return;
  }
  
  passwordError.value = "";
};

// 获取图形验证码
function getCode() {
  getCodeImg().then((res: any) => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = 'data:image/gif;base64,' + res.img
      modelForm.value.userInfo.uuid = res.uuid
    }
  })
};

// const changeInput = debounce(async function (event?: any) {
//   if(/[a-zA-Z]/.test(event)) {
//     modelForm.value.userInfo.mobile = "";
//     uni.$u.toast("禁止输入英文字母");
//   }
// }, 1000);

const navigateTo = (url: any) => {
  uni.navigateTo({
    url,
  });
};
// 初始化用户store和身份管理
const userStore = useUserStore();
const { initUserIdentity } = useUserIdentity();

const submit = async () => {
  console.log('登录按钮被点击');
  console.log('表单数据:', modelForm.value);
  console.log('表单引用:', formRef.value);
  
  try {
    console.log('开始表单验证...');
    const valid = await formRef.value.validate();
    console.log('表单验证结果:', valid);
    
    if (valid) {
      // 准备登录数据
      const loginData = {
        phone: modelForm.value.userInfo.mobile,
        password: modelForm.value.userInfo.password
      };
      
      console.log('开始登录，数据:', loginData);
      
      // 调用登录接口
      const response: any = await login(loginData);
      
      if (response.data.code === 200) {
        // 登录成功，保存用户信息
        const userInfo = response.data.data;
        const token = userInfo.token;
        
        // 设置用户登录信息
        userStore.setLoginInfo({
          userId: userInfo.userId,
          phone: userInfo.phone,
          token: token
        });
        
        // 保存token到多个地方（兼容性）
        uni.setStorageSync('drone_token', token);
        uni.setStorageSync('token', token);
        uni.setStorageSync('Authorization', token);
        
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        });
        
        // 关闭弹窗
        showPopup.value = false;
        
        // 初始化用户身份信息
        console.log('开始初始化用户身份信息...');
        const identityLoaded = await initUserIdentity();
        
        if (identityLoaded) {
          console.log('用户身份信息初始化成功');
        } else {
          console.log('用户身份信息初始化失败，但继续跳转');
        }
        
        // 跳转到首页
        setTimeout(() => {
          navigateTo(`/indexPages/index/index`);
        }, 1500);
      } else {
        uni.showToast({
          title: response.data.msg || '登录失败',
          icon: 'none'
        });
      }
    } else {
      uni.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
    }
  } catch (error: any) {
    console.error('登录失败:', error);
    uni.showToast({
      title: error.data?.msg || error.errMsg || '登录失败',
      icon: 'none'
    });
  }
};

getCode();
</script>

<style lang="scss" scoped>
.login {
  background-image: url("https://su.bcebos.com/b2b-jiameng/online/clear_pic/755117");
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center center;
  height: 100vh;
  .upbutton {
    width: 200px;
    position: fixed;
    bottom: 30%;
    left: calc(50% - 100px);
  }
}
.form {
  padding: 20px;
  .sign-up {
    display: flex;
    align-items: center;
    justify-content: center;

    text {
      margin: 0 20px;
      font-size: 20px;
      font-weight: bold;
      color: #9ca3af;
      &.active {
        position: relative;
        color: #1865da;
        &::after {
          position: absolute;
          content: "";
          width: 100%;
          height: 2px;
          bottom: -4px;
          left: 0;
          background-color: #1865da;
        }
      }
    }
  }
  .upform {
    margin: 20px 0;
  }
  .logo-text {
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #007aff;
    &.terms {
      font-size: 14px;
      justify-content: center !important;
      margin: 10px 0;
    }
    &.active {
      justify-content: flex-end;
    }
    &.other-logins {
      color: #9ca3af;
    }
  }
  .logon-footer {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 20px 0;
    text {
      font-size: 14px;
      color: #9ca3af;
      padding-top: 10px;
    }
  }
  
  .login-code {
    width: 30%;
    height: 40px;
    .login-code-img {
      height: 40px;
      width: 100%;
    }
  }
}
.company {
  font-size: 14px;
  text-align: center;
  color: #9ca3af;
  display: flex;
  flex-direction: column;
  padding-top: 50px;
  .text {
    padding-bottom: 5px;
  }
}

.error-tip {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  padding-left: 5px;
}
</style>
